package com.android;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.MediaStore;
import android.provider.Contacts.People;
import android.provider.MediaStore.Images;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.util.Log;


public class spotlight extends ListActivity {
    /** Called when the activity is first created. */
	private EditText query;
	private TextView text1;
	private Button searchbtn;
	private ArrayList<String> verIDList;
	private ArrayList<String> mergedList;
	private DBAdapter dba;
    private int num_results=0;
    private String qname;
    
    
    /************ onCreate() 
     			* Opens and clears the database 
     			* Captures the user OnClick/OnKey event and calls doSearch() 
     */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        query = (EditText) findViewById(R.id.query);
        text1 = (TextView) findViewById(R.id.text1);
        searchbtn = (Button) findViewById(R.id.search);
        dba=new DBAdapter(this);
        dba.open();
        //dba.deleteAll();
        
        /* This allows for quick searching as the user types */
        query.setOnKeyListener(new View.OnKeyListener(){
      		public boolean onKey(View v, int keyCode, KeyEvent event) {
					// TODO Auto-generated method stub
      				doSearch();
					return false;
				}

        });
  
        /* the normal button click listener for search */
        searchbtn.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view){
        		try{
        		doSearch();
        		}
        		catch(Exception e){
        			text1.setText(e.getMessage());
        		}
        	}
        });
       }

    
    /************ doSearch() 
    			* Searches the database first to get the data matching a query
    			* If not present gets the data from the containerList
    			* Displays the results in a ListAdapter
    			*/
  
    public void doSearch(){
    	
    	Cursor contactResult = getContacts();
    	Cursor imageResult = getImages();
    	verIDList= new ArrayList<String>();
    	mergedList = new ArrayList<String>();
       	verIDList.clear();
       	mergedList.clear();
       	num_results=0;
       	preProcess();
       	   	    	
    	/* Check if there is a result for contacts or if nothing to search */   	
    	if (contactResult!=null && contactResult.moveToFirst()&&(!query.getText().toString().equals(""))) {

            String name; 
            String contactID;
            int nameColumn = contactResult.getColumnIndex(People.NAME); 
            int contactIDcol = contactResult.getColumnIndex(People._ID);
           
            do {
                // Get the field values
            	if(! verIDList.contains("CON_"+contactResult.getString(contactIDcol)+"_"+
            		contactResult.getString(nameColumn)+"_"+contactResult.getString(contactIDcol))) {
            		name = contactResult.getString(nameColumn);
                	contactID = contactResult.getString(contactIDcol);
                	mergedList.add(name);
                   	verIDList.add("CON_"+contactID+"_"+name+"_"+contactID);
                	dba.updateNote("CON_"+contactID, name, contactID, qname);
                   	num_results++;
            	}
            } while (contactResult.moveToNext());

        }	
    	    	
    	// Do same for images 
    	
    	if (imageResult!=null && imageResult.moveToFirst()&&(!query.getText().toString().equals(""))) {

            String title; 
            String imageID;
            int titleColumn = imageResult.getColumnIndex(Images.ImageColumns.DISPLAY_NAME); 
            int imageIDcol = imageResult.getColumnIndex(Images.ImageColumns._ID);
            
            do {
                // Get the field values
            	if(! verIDList.contains("IMG_"+imageResult.getString(imageIDcol)+"_"+
            		  imageResult.getString(titleColumn)+"_"+imageResult.getString(imageResult.getColumnIndex(Images.ImageColumns.DATA)))) 
            		{
            		title = imageResult.getString(titleColumn);
            		imageID = imageResult.getString(imageIDcol);
            		mergedList.add(title);
               		verIDList.add("IMG_"+imageID+"_"+title+"_"+imageResult.getString(imageResult.getColumnIndex(Images.ImageColumns.DATA)));
            		dba.updateNote("IMG_"+imageID, title, imageResult.getString(imageResult.getColumnIndex(Images.ImageColumns.DATA)), qname);
            		num_results++;
            	}
            } while (imageResult.moveToNext());

        }	
    	   	
    	//closing the cursor after every search.
    	contactResult.close();
    	imageResult.close();
    	
       	/* Add this to the adapter */
    	ArrayAdapter<String> finalAdapter = new ArrayAdapter<String>(this, R.layout.contact_row, mergedList);
    	setListAdapter(finalAdapter);
    	text1.setText(num_results + " results found");
    }

    
    /****************** getContacts() 
     				  * Gets the contacts from the contacts database
     				  * Returns a cursor to the list of contacts
     */
    
    public Cursor getContacts(){
    		/* Which columns to return */
       		String[] projection = new String[] {
      				People._ID,
      				People.NAME,
      				People.NUMBER,
      			};
       			
       	 		Cursor managedCursor = managedQuery(
                 Contacts.People.CONTENT_URI,
                 projection,   // Which columns to return.
                 "People.NAME LIKE '"+query.getText().toString()+"%'",
                 null,          // WHERE clause.
                 People.NAME + " ASC");
       	 		qname=query.getText().toString();
    	 
    	 return managedCursor;
    	 
    }
    
    
    /****************** getImages() 
	  * Gets the images from the Images database
	  * Returns a cursor to the list of Images
	  */
    
    public Cursor getImages(){
    	
		String[] imageList = new String[] {
  				Images.ImageColumns.TITLE,
  				Images.ImageColumns._ID,
  				Images.ImageColumns.DISPLAY_NAME,
  				Images.ImageColumns.DATA
  				};
 	
    	Cursor imageCursor= managedQuery(
    			MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
    			imageList, 
    			"Images._DISPLAY_NAME LIKE '"+query.getText().toString()+"%'",
                null,          // WHERE clause.
                null);
    	qname=query.getText().toString();
      	return imageCursor;
    }
    
    
    /*************** onListItemClick()
     			   * Called when a user clicks a search result
     			   * Updates the hit count for the entry in the database
     			   * Then starts a new activity based on the type 
     */
    
    
    protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		String nameStarr=verIDList.get(position).split("_")[2];
		String nameIDarr=verIDList.get(position).split("_")[3];
		
		try {
				/* Call the activity to handle this intent */
			 if(verIDList.get(position).startsWith("CON")) {
				 Intent i = new Intent(Intent.ACTION_VIEW);
				 i.setData(Uri.parse("content://contacts/people/"+nameIDarr));
				 dba.updateNote("CON"+"_"+nameIDarr, nameStarr, nameIDarr, qname);
  	           	 startActivityForResult(i,0);
			 }
			 else {
				  	Intent i=new Intent(Intent.ACTION_VIEW);
	                i.setDataAndType(Uri.parse("file://"+nameIDarr),"image/*");
	                //startActivity(i);
				 	//Intent i = new Intent(this,ImageDisplay.class);
			        //i.putExtra("URIContent", nameIDarr);
    			  
	                dba.updateNote("IMG"+"_"+verIDList.get(position).split("_")[1], nameStarr, nameIDarr, qname);
    			 
	                startActivityForResult(i,1);  	        
			 }
		} catch (Exception e) {
			Log.e("EX15", e.toString());
		} 
	}
    

    /******* onActivityResult()
     	   * DoSearch() is called to arrange the search results according to their key hit
     */
    
    protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
    	doSearch();
}
    
    /************ preProcess()
     			* Searches the database for results matching the query
     			* Populated the result list with the search results
     */
   
    private void preProcess() {
    	Cursor c=dba.fetchNote(qname);
    	String name;
    	String phoneID;
    	String verID;
	
    	if(c.getCount()>0) {
    		do {
    			name = c.getString(c.getColumnIndex("name"));
    			phoneID = c.getString(c.getColumnIndex("phone"));
    			verID=c.getString(c.getColumnIndex("title"));
    			verIDList.add(verID+"_"+name+"_"+phoneID);
    			mergedList.add(name);
    			num_results++;
    		}while(c.moveToNext());
    	}
    }
    /** MENU  of the activity 
     *
     */
    public static final int Menu1 = Menu.FIRST + 1;
 
    /** create the menu items */
    public void populateMenu(Menu menu) {

      // enable keyb shortcuts, qwerty mode = true means only show keyb shortcuts (not numeric) and vice versa
      // these only show up in context menu, not options men
      MenuItem item1 = menu.add(0, Menu1, 0, "Delete Tweaks");
    }
    
    /** hook into menu button for activity */
    public boolean onCreateOptionsMenu(Menu menu) {
      populateMenu(menu);
      return super.onCreateOptionsMenu(menu);
    }

    /** when menu button option selected */
    public boolean onOptionsItemSelected(MenuItem item) {
      return applyMenuChoice(item) || super.onOptionsItemSelected(item);
    }
    /** respond to menu item selection */
    public boolean applyMenuChoice(MenuItem item) {
      switch (item.getItemId()) {
        case Menu1:
          dba.deleteAll();
          return true;
      }
      return false;
    }
    
    /********* onStop()
             * Close the database during exit
     */
    
    protected void onDestroy() {
        super.onDestroy();
        dba.close();
    }
    
}

